import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { 
  Card, Table, Tag, Space, Button, Input, Select, 
  Modal, Descriptions, Typography, Row, Col, Statistic, 
  message, Tooltip, Divider
} from 'antd';
import { 
  SearchOutlined, InfoCircleOutlined, BugOutlined, 
  DatabaseOutlined, AlertOutlined, ReloadOutlined,
  PlusOutlined, EditOutlined, DeleteOutlined, 
  PlayCircleOutlined, PauseCircleOutlined
} from '@ant-design/icons';
import { 
  getCompatibilityRules, 
  CompatibilityRule,
  toggleCompatibilityRuleStatus,
  deleteCompatibilityRule,
  batchUpdateRuleStatus
} from '../../services/api';
import RuleFormModal from '../../components/RuleFormModal/RuleFormModal';
import './Rules.css';

const { Title, Text } = Typography;
const { Option } = Select;

const RulesPage: React.FC = () => {
  const [rules, setRules] = useState<CompatibilityRule[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [filters, setFilters] = useState({
    sourceDbType: undefined as string | undefined,
    targetDbType: undefined as string | undefined,
    severity: undefined as string | undefined,
    category: undefined as string | undefined,
    search: ''
  });
  const [selectedRule, setSelectedRule] = useState<CompatibilityRule | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  
  // RuleFormModal状态管理
  const [formModalVisible, setFormModalVisible] = useState(false);
  const [formMode, setFormMode] = useState<'create' | 'edit'>('create');
  const [editingRule, setEditingRule] = useState<CompatibilityRule | null>(null);
  
  // 获取用户信息和权限
  const getUserInfo = () => {
    try {
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr) {
        return JSON.parse(userInfoStr);
      }
    } catch (error) {
      console.warn('Failed to parse user info');
    }
    return null;
  };
  
  const userInfo = getUserInfo();
  const isAdmin = userInfo?.role === 'ADMIN';
  
  // 防抖搜索 - 使用 useRef 避免依赖问题
  const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const filtersRef = useRef(filters);
  const paginationRef = useRef(pagination);
  
  // 保持 ref 与状态同步
  filtersRef.current = filters;
  paginationRef.current = pagination;
  
  // 获取规则列表 - 使用 useRef 避免依赖地狱
  const fetchRules = useCallback(async (customParams: {
    filters?: typeof filters;
    pagination?: typeof pagination;
  } = {}) => {
    setLoading(true);
    try {      
      const currentFilters = customParams.filters || filtersRef.current;
      const currentPagination = customParams.pagination || paginationRef.current;
      
      const response = await getCompatibilityRules({
        ...currentFilters,
        current: currentPagination.current,
        size: currentPagination.pageSize
      });
      
      if (response.success) {
        setRules(response.data.records || []);
        setPagination(prev => ({ ...prev, total: response.data.total || 0 }));
      } else {
        message.error(response.message || '获取规则失败');
      }
    } catch (error: any) {
      console.error('获取规则失败:', error);
      message.error(error.message || '获取规则失败');
    } finally {
      setLoading(false);
    }
  }, []); // 使用 ref 避免依赖问题
  
  const handleSearchInputChange = useCallback((value: string) => {
    // 立即更新UI状态
    setFilters(prev => ({ ...prev, search: value }));
    
    // 清除之前的定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
    
    // 设置新的防抖定时器 - 自动触发搜索
    searchTimeoutRef.current = setTimeout(() => {
      const newPagination = { ...paginationRef.current, current: 1 };
      setPagination(newPagination);
      // 使用最新的 filters 值进行搜索
      const currentFilters = { ...filtersRef.current, search: value };
      fetchRules({ 
        filters: currentFilters,
        pagination: newPagination
      });
    }, 500);
  }, [fetchRules]);

  // 处理搜索和筛选
  const handleSearch = useCallback(() => {
    const newPagination = { ...paginationRef.current, current: 1 };
    setPagination(newPagination);
    fetchRules({ 
      filters: filtersRef.current,
      pagination: newPagination
    });
  }, [fetchRules]);

  // 重置筛选
  const handleReset = useCallback(() => {
    const resetFilters = { sourceDbType: undefined, targetDbType: undefined, severity: undefined, category: undefined, search: '' };
    const resetPagination = { ...paginationRef.current, current: 1 };
    setFilters(resetFilters);
    setPagination(resetPagination);
    // 清除防抖定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
    // 立即执行搜索
    setTimeout(() => fetchRules({
      filters: resetFilters,
      pagination: resetPagination
    }), 50);
  }, [fetchRules]);

  // 管理员操作函数
  const handleAddRule = () => {
    setFormMode('create');
    setEditingRule(null);
    setFormModalVisible(true);
  };

  const handleEditRule = (rule: CompatibilityRule) => {
    setFormMode('edit');
    setEditingRule(rule);
    setFormModalVisible(true);
  };

  const handleFormSuccess = useCallback(() => {
    setFormModalVisible(false);
    setEditingRule(null);
    fetchRules({ 
      filters: filtersRef.current,
      pagination: paginationRef.current
    }); // 重新加载数据
  }, [fetchRules]);

  const handleFormCancel = () => {
    setFormModalVisible(false);
    setEditingRule(null);
  };

  const handleToggleRuleStatus = async (rule: CompatibilityRule) => {
    try {
      const response = await toggleCompatibilityRuleStatus(rule.id);
      if (response.success) {
        message.success(`规则已${rule.isActive ? '禁用' : '启用'}`);
        // 更新本地数据
        setRules(prevRules => 
          prevRules.map(r => 
            r.id === rule.id ? { ...r, isActive: !r.isActive } : r
          )
        );
      } else {
        message.error(response.message || '操作失败');
      }
    } catch (error: any) {
      console.error('切换规则状态失败:', error);
      message.error(error.message || '操作失败');
    }
  };

  const handleDeleteRule = (rule: CompatibilityRule) => {
    Modal.confirm({
      title: '确认删除规则',
      content: `确定要删除规则 "${rule.ruleName}" 吗？删除后无法恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deleteCompatibilityRule(rule.id);
          if (response.success) {
            message.success('规则删除成功');
            // 重新加载数据
            fetchRules({ 
              filters: filtersRef.current,
              pagination: paginationRef.current
            });
          } else {
            message.error(response.message || '删除失败');
          }
        } catch (error: any) {
          console.error('删除规则失败:', error);
          message.error(error.message || '删除失败');
        }
      }
    });
  };

  const handleBatchStatusChange = async (status: boolean) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要操作的规则');
      return;
    }
    
    try {
      const response = await batchUpdateRuleStatus({
        ruleIds: selectedRowKeys as number[],
        isActive: status
      });
      
      if (response.success) {
        message.success(`批量${status ? '启用' : '禁用'}成功`);
        // 清空选择
        setSelectedRowKeys([]);
        // 重新加载数据
        fetchRules({ 
          filters: filtersRef.current,
          pagination: paginationRef.current
        });
      } else {
        message.error(response.message || '批量操作失败');
      }
    } catch (error: any) {
      console.error('批量操作失败:', error);
      message.error(error.message || '批量操作失败');
    }
  };

  // 统计信息
  const getStatistics = () => {
    const total = rules.length;
    const high = rules.filter(r => r.severity === 'HIGH').length;
    const medium = rules.filter(r => r.severity === 'MEDIUM').length;
    const low = rules.filter(r => r.severity === 'LOW').length;
    const info = rules.filter(r => r.severity === 'INFO').length;
    
    return { total, high, medium, low, info };
  };

  // 表格列定义
  const columns = [
    {
      title: '规则ID',
      dataIndex: 'ruleId',
      key: 'ruleId',
      width: 100,
      render: (text: string) => <Tag color="blue" className="rule-id-tag">{text}</Tag>
    },
    {
      title: '规则名称',
      dataIndex: 'ruleName',
      key: 'ruleName',
      width: 180,
      render: (text: string, record: CompatibilityRule) => (
        <Button 
          type="link" 
          onClick={() => {
            setSelectedRule(record);
            setDetailModalVisible(true);
          }}
          className="rule-name-link"
          style={{
            padding: 0,
            height: 'auto',
            fontWeight: 500,
            textAlign: 'left',
            whiteSpace: 'normal',
            wordBreak: 'break-all',
            lineHeight: '1.4',
            display: '-webkit-box',
            WebkitBoxOrient: 'vertical',
            WebkitLineClamp: 2,
            overflow: 'hidden',
            maxHeight: '2.8em'
          }}
        >
          {text}
        </Button>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 100,
      render: (text: string) => <Tag color="green">{text}</Tag>
    },
    {
      title: '数据库类型',
      key: 'databaseType',
      width: 160,
      render: (record: CompatibilityRule) => (
        <Row gutter={[8, 4]} className="database-type-columns">
          <Col span={12}>
            <div className="db-type-item">
              <Text type="secondary" style={{ fontSize: '12px' }}>源库</Text>
              <Tag color="orange" style={{ fontSize: '12px', padding: '0 4px' }}>{record.sourceDbType}</Tag>
            </div>
          </Col>
          <Col span={12}>
            <div className="db-type-item">
              <Text type="secondary" style={{ fontSize: '12px' }}>目标库</Text>
              <Tag color="purple" style={{ fontSize: '12px', padding: '0 4px' }}>{record.targetDbType}</Tag>
            </div>
          </Col>
        </Row>
      )
    },
    {
      title: '问题描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text} placement="topLeft">
          <Text ellipsis style={{ maxWidth: '180px' }}>{text}</Text>
        </Tooltip>
      )
    },
    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      width: 100,
      render: (severity: string) => {
        const colors: Record<string, string> = { 
          HIGH: 'red', 
          MEDIUM: 'orange', 
          LOW: 'yellow', 
          INFO: 'blue' 
        };
        const texts: Record<string, string> = {
          HIGH: '高危',
          MEDIUM: '中危', 
          LOW: '低危',
          INFO: '信息'
        };
        return <Tag color={colors[severity] || 'default'} className="severity-tag">
          {texts[severity] || severity}
        </Tag>;
      }
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 80,
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'green' : 'red'} className="status-tag">
          {isActive ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: isAdmin ? 160 : 80,
      render: (record: CompatibilityRule) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small"
            icon={<InfoCircleOutlined />}
            onClick={() => {
              setSelectedRule(record);
              setDetailModalVisible(true);
            }}
          >
            详情
          </Button>
          {isAdmin && (
            <>
              <Button 
                type="link" 
                size="small"
                icon={<EditOutlined />}
                onClick={() => handleEditRule(record)}
              >
                编辑
              </Button>
              <Button 
                type="link" 
                size="small"
                icon={record.isActive ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                onClick={() => handleToggleRuleStatus(record)}
              >
                {record.isActive ? '禁用' : '启用'}
              </Button>
              <Button 
                type="link" 
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={() => handleDeleteRule(record)}
              >
                删除
              </Button>
            </>
          )}
        </Space>
      )
    }
  ];

  // 筛选器组件 - 使用 useMemo 稳定化组件渲染
  const FilterSection = useMemo(() => (
    <Card className="filter-card" bodyStyle={{ padding: '16px 24px' }}>
      <Row gutter={[16, 16]} align="middle">
        <Col flex="auto">
          <Space size="middle">
            <Input
              placeholder="搜索规则名称或ID"
              prefix={<SearchOutlined />}
              value={filters.search}
              onChange={(e) => handleSearchInputChange(e.target.value)}
              allowClear
              style={{ width: 200 }}
              autoComplete="off"
            />
            <Select
              placeholder="源数据库类型"
              value={filters.sourceDbType}
              onChange={(value) => setFilters(prev => ({ ...prev, sourceDbType: value }))}
              allowClear
              style={{ width: 140 }}
            >
              <Option value="MYSQL">MySQL</Option>
              <Option value="ORACLE">Oracle</Option>
              <Option value="POSTGRESQL">PostgreSQL</Option>
              <Option value="SQLSERVER">SQL Server</Option>
            </Select>
            <Select
              placeholder="目标数据库类型"
              value={filters.targetDbType}
              onChange={(value) => setFilters(prev => ({ ...prev, targetDbType: value }))}
              allowClear
              style={{ width: 140 }}
            >
              <Option value="GOLDENDB">GoldenDB</Option>
              <Option value="MYSQL">MySQL</Option>
            </Select>
            <Select
              placeholder="严重程度"
              value={filters.severity}
              onChange={(value) => setFilters(prev => ({ ...prev, severity: value }))}
              allowClear
              style={{ width: 100 }}
            >
              <Option value="HIGH">高危</Option>
              <Option value="MEDIUM">中危</Option>
              <Option value="LOW">低危</Option>
              <Option value="INFO">信息</Option>
            </Select>
            <Select
              placeholder="规则分类"
              value={filters.category}
              onChange={(value) => setFilters(prev => ({ ...prev, category: value }))}
              allowClear
              style={{ width: 120 }}
            >
              <Option value="SYNTAX">语法</Option>
              <Option value="FUNCTION">函数</Option>
              <Option value="DATA_TYPE">数据类型</Option>
              <Option value="PERFORMANCE">性能</Option>
            </Select>
          </Space>
        </Col>
        <Col>
          <Space>
            <Button type="primary" onClick={handleSearch}>
              筛选
            </Button>
            <Button onClick={handleReset}>
              重置
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => fetchRules({ 
                filters: filtersRef.current,
                pagination: paginationRef.current
              })}
              loading={loading}
            >
              刷新
            </Button>
            {isAdmin && (
              <>
                <Divider type="vertical" />
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />}
                  onClick={handleAddRule}
                >
                  新增规则
                </Button>
              </>
            )}
          </Space>
        </Col>
      </Row>
      
      {/* 批量操作区域 - 仅管理员可见 */}
      {isAdmin && selectedRowKeys.length > 0 && (
        <>
          <Divider style={{ margin: '12px 0' }} />
          <Row>
            <Col>
              <Space>
                <Text>已选择 {selectedRowKeys.length} 项</Text>
                <Button 
                  size="small"
                  icon={<PlayCircleOutlined />}
                  onClick={() => handleBatchStatusChange(true)}
                >
                  批量启用
                </Button>
                <Button 
                  size="small"
                  icon={<PauseCircleOutlined />}
                  onClick={() => handleBatchStatusChange(false)}
                >
                  批量禁用
                </Button>
              </Space>
            </Col>
          </Row>
        </>
      )}
    </Card>
  ), [filters, isAdmin, selectedRowKeys, handleSearch, handleReset, fetchRules, loading, handleSearchInputChange, handleBatchStatusChange]);

  // 统计卡片
  const StatisticsSection = () => {
    const stats = getStatistics();
    return (
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="总规则数"
              value={stats.total}
              prefix={<BugOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="高危规则"
              value={stats.high}
              prefix={<AlertOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="中危规则"
              value={stats.medium}
              prefix={<AlertOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="低危规则"
              value={stats.low + stats.info}
              prefix={<InfoCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>
    );
  };

  // 规则详情模态框
  const RuleDetailModal = () => (
    <Modal
      title="规则详情"
      open={detailModalVisible}
      onCancel={() => setDetailModalVisible(false)}
      footer={null}
      width={900}
      className="detail-modal"
    >
      {selectedRule && (
        <Descriptions column={2} bordered size="middle">
          <Descriptions.Item label="规则ID" span={2}>
            <Tag color="blue" className="rule-id-tag">{selectedRule.ruleId}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="规则名称" span={2}>
            <Text strong style={{ fontSize: '16px' }}>{selectedRule.ruleName}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="分类">
            <Tag color="green">{selectedRule.category}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="严重程度">
            <Tag color={selectedRule.severity === 'HIGH' ? 'red' : 
                        selectedRule.severity === 'MEDIUM' ? 'orange' : 
                        selectedRule.severity === 'LOW' ? 'yellow' : 'blue'}>
              {selectedRule.severity === 'HIGH' ? '高危' :
               selectedRule.severity === 'MEDIUM' ? '中危' :
               selectedRule.severity === 'LOW' ? '低危' : '信息'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="源数据库类型">
            <Space>
              <DatabaseOutlined style={{ color: '#fa8c16' }} />
              <Tag color="orange">{selectedRule.sourceDbType}</Tag>
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="目标数据库类型">
            <Space>
              <DatabaseOutlined style={{ color: '#722ed1' }} />
              <Tag color="purple">{selectedRule.targetDbType}</Tag>
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="状态" span={2}>
            <Tag color={selectedRule.isActive ? 'green' : 'red'} className="status-tag">
              {selectedRule.isActive ? '启用' : '禁用'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="规则模式" span={2}>
            <Text code className="rule-pattern-code">
              {selectedRule.rulePattern}
            </Text>
          </Descriptions.Item>
          <Descriptions.Item label="问题描述" span={2}>
            <Text>{selectedRule.description}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="修改建议" span={2}>
            <Text>{selectedRule.suggestion}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="示例SQL" span={2}>
            <Text code className="example-sql-code">
              {selectedRule.exampleSql}
            </Text>
          </Descriptions.Item>
          <Descriptions.Item label="建议SQL" span={2}>
            <Text code className="suggested-sql-code">
              {selectedRule.suggestedSql}
            </Text>
          </Descriptions.Item>
        </Descriptions>
      )}
    </Modal>
  );

  useEffect(() => {
    fetchRules();
  }, [fetchRules]); // 添加 fetchRules 依赖

  return (
    <div className="rules-page">
      {/* 页面头部 */}
      <div className="page-header">
        <Space align="center">
          <BugOutlined style={{ fontSize: 24, color: '#1890ff' }} />
          <Title level={3} className="rules-title">
            兼容性规则库
            {isAdmin ? (
              <Tag color="gold" style={{ marginLeft: 8 }}>管理员视图</Tag>
            ) : (
              <Tag color="blue" style={{ marginLeft: 8 }}>用户视图</Tag>
            )}
          </Title>
        </Space>
        <Text type="secondary" className="rules-description">
          {isAdmin ? '管理和维护SQL兼容性检查规则' : '查看当前系统配置的所有SQL兼容性检查规则'}
        </Text>
      </div>

      {/* 统计卡片 */}
      <StatisticsSection />
      
      {/* 筛选器 */}
      {FilterSection}

      {/* 规则列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={rules}
          rowKey="id"
          loading={loading}
          locale={{
            emptyText: (
              <div style={{ padding: '40px 0' }}>
                <BugOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
                <div style={{ marginTop: 16, color: '#999' }}>
                  {filters.search || filters.sourceDbType || filters.targetDbType || 
                   filters.severity || filters.category ? 
                   '没有找到符合条件的规则' : '暂无兼容性规则'}
                </div>
                {isAdmin && !filters.search && !filters.sourceDbType && !filters.targetDbType && 
                 !filters.severity && !filters.category && (
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />}
                    style={{ marginTop: 16 }}
                    onClick={handleAddRule}
                  >
                    创建第一个规则
                  </Button>
                )}
              </div>
            )
          }}
          rowSelection={isAdmin ? {
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            getCheckboxProps: (record) => ({
              name: record.ruleName,
            }),
          } : undefined}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条规则`,
            onChange: (page, pageSize) => {
              const newPagination = { 
                ...paginationRef.current, 
                current: page, 
                pageSize: pageSize || 10 
              };
              setPagination(newPagination);
              fetchRules({ 
                filters: filtersRef.current,
                pagination: newPagination
              });
            }
          }}
          scroll={{ x: 1400 }}
          className="rule-table"
        />

        <RuleDetailModal />
        
        {/* 规则表单模态框 - 仅管理员可用 */}
        {isAdmin && (
          <RuleFormModal
            visible={formModalVisible}
            mode={formMode}
            initialValues={editingRule || undefined}
            onSuccess={handleFormSuccess}
            onCancel={handleFormCancel}
          />
        )}
      </Card>
    </div>
  );
};

export default RulesPage;
